﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using eOfficeDevManager;
using System.Data;
using System.IO.Ports;

namespace eOfficeDev
{
    public class eOfficeImpl :IDataInterface
    {
        SerialPort _sPort = new SerialPort();
        DeviceHandler _devInfo = new DeviceHandler();
        DateTime trsTime;
        public DataSet DownLoadData(DataSet columnHeadings)
        {
            if (Init(_devInfo))
            {
                try
                {
                    int iRetVal;
                    int _Status;
                    string _strCmd, _strResp;
                    char[] chSpliters = new char[] { ' ', ',', '#' };
                    string[] strTockens;
                    string _strDate;
                    trsTime = DateTime.Now;
                    for (int i = 0; i < 5; i++)
                    {
                        _strCmd = "LG " + i.ToString() + "\r";
                        _strResp = "";
                        iRetVal = SendCommand(_strCmd, ref _strResp);
                        //if (iRetVal == -1) return;
                        //if (iRetVal < 0) continue;
                        strTockens = _strResp.Split(chSpliters);

                        DataRow dr = columnHeadings.Tables[0].NewRow();
                        dr["Id"] = Convert.ToInt32(strTockens[2].ToString());
                        _strDate = "'" + strTockens[4] + "/" + strTockens[5] + "/";
                        int logYear;
                        if ((trsTime.Month == 1) && (int.Parse(strTockens[4]) > trsTime.Month))
                            logYear = trsTime.Year - 1;
                        else logYear = trsTime.Year;
                        strTockens[8] = strTockens[8].TrimEnd('\r');
                        _strDate = _strDate + logYear.ToString() + " ";
                        _strDate = _strDate + strTockens[6] + ":" + strTockens[7] + ":" + strTockens[8] + "')";
                        dr["DateTime"] = _strDate;
                        dr["In/Out"] = Convert.ToInt32(strTockens[3].ToString());
                        _Status = 0;
                        dr["Status"] = _Status;
                        columnHeadings.Tables[0].Rows.Add(dr);
                        _sPort.Close();
                        
                    }

                }
                
                catch (Exception exp)
                {
                    eOfficeDevManager.eOfficeDevManager eOffDev = new eOfficeDevManager.eOfficeDevManager();
                    eOffDev.LogWrite(exp.ToString());
                }
            }
            return columnHeadings;
        }

        public bool Init(DeviceHandler _devInfo)
        {
            //try
            //{
            //    if(_sPort.IsOpen)
            //    _sPort.Close();
            //    _sPort.PortName = _devInfo.DevicePort;
            //    _sPort.BaudRate = Convert.ToInt32(_devInfo.BaudRate);
            //    _sPort.DataBits = 8;
            //    _sPort.Parity = Parity.None;
            //    _sPort.StopBits = StopBits.One;
            //    _sPort.ReadTimeout = 1000;
            //    _sPort.Handshake = Handshake.None;
            //    _sPort.ReceivedBytesThreshold = 20;
            //    _sPort.Open();
                
            //    return true;
            //}
            //catch (Exception ex)
            //{
            //    return false;
            //}

            return true;
        }

        public int SendCommand(string strCommand, ref string _strRep)
        {
            if (!_sPort.IsOpen) 
            { //("Port Not Open,Send Command returning\r\n"); 
                return 0;
            }
            string _strLog;
            string _strCmd = strCommand.Substring(0, 2);
           
            //WriteLog("Sending Command:");
            //WriteLog(strCommand);
            //WriteLog("\r\n");         

            WriteToPort(strCommand);
            while (true)
            {
                try
                {
                    //if (_DispLog) Application.DoEvents();
                    //WriteLog("waiting for response\r\n");
                    _strRep = _sPort.ReadLine();
                    _strLog = _strRep + "\r\n";

                    
                    //WriteLog("Response Rcvd:");
                    //WriteLog(strRep);
                    //WriteLog("\r\n");

                    if ((_strRep.StartsWith(_strCmd)) || (_strRep.StartsWith("RE")))
                    {
                        //if (_LogFileSts)
                        //{
                        //    WriteLog("Positive Reply Command exec Sucess!!!\r\n");
                        //}
                        return 1;
                    }

                    if (_strRep.StartsWith("FL"))
                    {
                        //if (_LogFileSts)
                        //{
                        //    WriteLog("Command exec failed\r\n");
                        //}

                        return -1;
                    }

                    continue;
                }
                catch (SystemException exp)
                {
                    //WriteLog("Timeout or Read error\r\n");
                    return -2;
                }
            }
        }
        void WriteToPort(string strCMD)
        {
            if (!_sPort.IsOpen) return;
            byte[] byArr = new byte[1];

            for (int i = 0; i < strCMD.Length; ++i)
            {

                byArr[0] = (byte)strCMD[i];
                _sPort.Write(byArr, 0, 1);
                //Thread.Sleep(100);

            }
            //Thread.Sleep(500);
        }

        public bool DeleteLog(DataSet logToDelete)
        {
            return true;
        }
        public DataSet DownLoadUserData(bool newOnly)
        {
            return new DataSet();
        }

        public bool IsEventSupported()
        {
            return false;
        }
        public event EventHandler UpdateDeviceStatus;
        public event EventHandler CollectLogEvent;
    }
}
